package client

import (
	"github.com/golang/glog"
	//	"github.com/oikomi/FishChatServer2/protocol/rpc"
	//"github.com/oikomi/FishChatServer2/server/access/conf"
	//	sd "github.com/oikomi/FishChatServer2/service_discovery/etcd"
	//	"golang.org/x/net/context"
	"github.com/oikomi/FishChatServer2/server/access/conf_discovery"
	"google.golang.org/grpc"
	"time"
)

type LogicRPCCli struct {
	conns map[string]*grpc.ClientConn
}

func NewLogicRPCCli() (logicRpcCli *LogicRPCCli, err error) {
	glog.Info("NewlogicRpcCli")
	var logicServerList []string
	conns := make(map[string]*grpc.ClientConn)
	for {
		if len(conf_discovery.LogicServerList) <= 0 {
			time.Sleep(time.Second * 5)
		} else {
			glog.Info(conf_discovery.LogicServerList)
			for _, v := range conf_discovery.LogicServerList {
				logicServerList = append(logicServerList, v.IP)
			}
			for _, logicServer := range logicServerList {
				conn, err := grpc.Dial(logicServer, grpc.WithInsecure())
				if err != nil {
					glog.Error(err)
				}
				conns[logicServer] = conn
			}
			logicRpcCli = &LogicRPCCli{
				conns: conns,
			}
			break
		}
	}
	go logicRpcCli.connProc()
	return
}

func (logicRpcCli *LogicRPCCli) connProc() {
	glog.Info(conf_discovery.LogicServerList)
	var logicServerList []string
	conns := make(map[string]*grpc.ClientConn)
	for {
		for _, v := range conf_discovery.LogicServerList {
			glog.Info(v.IP)
			logicServerList = append(logicServerList, v.IP)
		}
		for _, logicServer := range logicServerList {
			conn, err := grpc.Dial(logicServer, grpc.WithInsecure())
			if err != nil {
				glog.Error(err)
			}
			conns[logicServer] = conn
		}
		logicRpcCli.conns = conns
		time.Sleep(time.Second * 10)
	}
}
